from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.

# 组织数据列表
from notice.models import Notice


def get_topic_list(topics):
    data = []
    for t in topics:
        dic = {
            "id": t.id,
            "title": t.title,
            "created_time": t.created_time,
            "introduce": t.introduce,
        }
        data.append(dic)
    return data


# 处理请求


def index_topic_list(request, cate):
    topics = Notice.objects.all()
    result = {
        "code": 200,
        "topics": get_topic_list(topics)
    }
    return JsonResponse(result)


def topic_content(request, name):
    # 文章是否存在
    t_id = request.GET.get("t_id")
    try:
        topic = Notice.objects.get(pk=t_id)
    except Exception as e:
        result = {'code': 10302, 'error': "the topic is not existed!"}
        return JsonResponse(result)

    # 返回文章详情
    result = {'code': 200, 'data': {'nickname': "admin"}}
    result['data']['title'] = topic.title
    result['data']['created_time'] = topic.created_time
    result['data']['content'] = topic.content
    result['data']['introduce'] = topic.introduce

    return JsonResponse(result)
